﻿<#
MIT License
Copyright (c) 2016 powershell-kitchen.com
http://www.powershell-kitchen.com/page/mit-license
Published on: http://powershell-kitchen.com/post/split-csvfile
#>

<#
  .SYNOPSIS
      split a csv file into mutiple files of an specific number of lines.
  .DESCRIPTION
      Splits a file csv into multiple files with the same name but with a numeric suffix.
  .EXAMPLE
      Split-CSVFile c:\temp\myFile.csv 1000
  .PARAMETER filePath
      file to be used as source
  .PARAMETER linesPerFile
      number of lines per file

  #>

Param(
  [Parameter(Mandatory=$True,Position=1)]
  [string]$filePath,
  [string]$linesPerFile =1150
)

$file = Get-Item $filePath
$fileFolder = $file.DirectoryName

$content = Get-Content $file
$csvheader = $content[0]
$lines = $content.Count
$filepart = 1
$currentSourceLine = 1
$currentDestinationLine = 0
$currentFile = 1
$currentFileName = $null
$start = 1
$sb = new-Object System.Text.StringBuilder

while ($currentSourceLine -lt $content.Length) {
    if  ($currentDestinationLine -eq 0)
    {
        if ($currentFileName -ne $null)
        {
            set-content $currentFileName $sb.ToString()
            [void]$sb.Clear();
        }
        $currentFileName = $fileFolder + "\" +$file.BaseName + "-$currentFile" + $file.Extension
        [void]$sb.AppendLine($csvheader);
        $currentDestinationLine++
        continue;
    }
    [void]$sb.AppendLine($content[$currentSourceLine])
    $currentSourceLine++
    $currentDestinationLine++
    if ($currentDestinationLine -gt $linesPerFile)
    {
        $currentDestinationLine = 0
        $currentFile++
    }
}

if ($currentFileName -ne $null -and $sb.Length -gt 0)
{
    set-content $currentFileName $sb.ToString()
}

